package m.jclecai.com.dialog;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.listener.OnSclestListener;
import m.jclecai.com.utils.ScreenUtil;
import m.jclecai.com.utils.http.FastOk;

/**
 * Created by ZD on 2017/5/4.
 * <p>
 * 精彩篮球的对话框
 */

public class JclqHHDialog extends BaseDialog {
    @BindView(R.id.homeTeamName)
    TextView mHomeTeamName;

    @BindView(R.id.awayTeamName)
    TextView mAwayTeamName;

    @BindView(R.id.tv_bf)
    TextView mTvBf;

    @BindView(R.id.rl_sf)
    RelativeLayout mRlSf;

    @BindView(R.id.ll_sf_container)
    LinearLayout mLlSfContainer;

    @BindView(R.id.tv_zjq)
    TextView mTvZjq;

    @BindView(R.id.rl_rsf)
    RelativeLayout mRlRsf;

    @BindView(R.id.ll_rsf_container)
    LinearLayout mLlRsfContainer;

    @BindView(R.id.tv_bqc)
    TextView mTvBqc;

    @BindView(R.id.rl_dxf)
    RelativeLayout mRlDxf;

    @BindView(R.id.ll_dxf_container)
    LinearLayout mLlDxfContainer;

    @BindView(R.id.tv_sfc)
    TextView mTvSfc;

    @BindView(R.id.rl_sfc)
    RelativeLayout mRlSfc;

    @BindView(R.id.ll_sfc_container)
    LinearLayout mLlSfcContainer;

    @BindView(R.id.tv_cancel)
    TextView mTvCancel;

    @BindView(R.id.tv_sure)
    TextView mTvSure;


    /**
     * 显示模式枚举出来；
     * 枚举，胜负，让胜负，大小分，全部显示，单关，胜分差
     */
    public enum JCZQSHOWTYPE {
        SHOWSF, SHOWRSF, SHOWDXF, SHOWALL, SHOWDG, SHOWSFC, SHOWHUNTOU
    }

    JCZQSHOWTYPE type = JCZQSHOWTYPE.SHOWALL;

    //red_white_selecter 的边线宽度
    int splitWidth = 0;

    String[] codes;
    List<String[]> list;
    Map<String, Map<String, String>> map;

    public JclqHHDialog(Context context, String[] codes, Map<String, Map<String, String>> map, JCZQSHOWTYPE type) {
        super(context);
        this.mContext = context;
        this.codes = codes;
        this.list = FastOk.getList(codes[15], String[].class);
   /*     if (type.equals(JCZQSHOWTYPE.SHOWSFC))
            this.list = FastOk.getList(codes[15], String[].class);
        else
            this.list = FastOk.getList(codes[16], String[].class);*/
        this.map = map;
        this.type = type;
        if (this.map == null)
            this.map = new HashMap<>();
        initView();
    }


    private void initView() {
        setContentView(R.layout.dialog_jclq_hh);

        initHeader();

        if (list == null || (list != null && list.size() <= 0)) {
            return;
        }

        //获取分割线的大小；
        splitWidth = ScreenUtil.dpToPx(mContext, 0.5f);
        //每个格子的大小；
        int height = ScreenUtil.dpToPx(mContext, 40);
        //获取屏幕的大小；
        int width = ScreenUtil.getScreenWidth(mContext) - ScreenUtil.dip2px(mContext, 60);

        int vWidth = 0;
        switch (type) {
            //全部显示；
            case SHOWHUNTOU:
                showAll(height, width, true);
                break;
            case SHOWALL:
                showAll(height, vWidth, false);
                break;
            case SHOWSF:
                //显示胜负
                mLlSfContainer.setVisibility(View.VISIBLE);
                vWidth = width / 2;
                addSF(vWidth, height, "0_sf_");
                break;
            case SHOWRSF:
                //显示让胜负
                mLlRsfContainer.setVisibility(View.VISIBLE);
                vWidth = width / 2;
                addRSF(vWidth, height, "1_rfsf_");
                break;
            case SHOWDXF:
                //显示大小分
                mLlDxfContainer.setVisibility(View.VISIBLE);
                vWidth = width / 2;
                addDXF(vWidth, height, "2_dxf_");

            case SHOWSFC:
                //胜利分差
                mLlSfcContainer.setVisibility(View.VISIBLE);
                String[] sfc = mContext.getResources().getStringArray(
                        R.array.jclq_sfc);
                String[] sfcValue = mContext.getResources().getStringArray(
                        R.array.jclq_sfc_value);
                mRlSfc.setVisibility(View.VISIBLE);
                vWidth = width / 3;
                addSFC(sfc, sfcValue, vWidth, height, 3, "3_sfc_", 7);
                break;
            case SHOWDG:
                //单关
                //这里的话，我们是需要判断一下，这种玩法是否有单关，比如让胜平负是没有单关的，比分，总进球之类的是永远有的单关；

            /*    width = ScreenUtil.getScreenWidth(mContext) - ScreenUtil.dip2px(mContext, 60);
                llSPFContainer.setVisibility(View.VISIBLE);
                llBFContainer.setVisibility(View.VISIBLE);
                llZJQContainer.setVisibility(View.VISIBLE);
                llBQCContainer.setVisibility(View.VISIBLE);
                vWidth = width / 3;
                //在在这里我们要判断一下是否支持单关，如果支持了，我们才显示；
                if (isSupportDanguan("spf")) {
                    addSPF(spf, vWidth, height, 3, "0_spf_", llSpf, 0);        //胜负彩；
                } else {
                    TextView tvSpf = new TextView(mContext);
                    tvSpf.setText("未开售单关固赔率");
                    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    tvSpf.setLayoutParams(layoutParams);
                    tvSpf.setEnabled(false);
                    tvSpf.setGravity(Gravity.CENTER);
                    tvSpf.setTextSize(12);
                    tvSpf.setPadding(0, 10, 0, 10);
                    tvSpf.setBackground(mContext.getResources().getDrawable(R.drawable.red_white_selecter));
                    llSpf.addView(tvSpf);
                }
                //让球胜负彩是没有单关的；
                TextView textView = new TextView(mContext);
                textView.setText("未开售单关固赔率");
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                textView.setLayoutParams(layoutParams);
                textView.setEnabled(false);
                textView.setGravity(Gravity.CENTER);
                textView.setTextSize(12);
                textView.setPadding(0, 10, 0, 10);
                textView.setBackground(mContext.getResources().getDrawable(R.drawable.red_white_selecter));
                llRQSpf.addView(textView);
                //addSPF(spf, vWidth, height, 3,"1_rqspf_",llRQSpf,1);    //让球胜负彩
                vWidth = width / 5;
                addBF(cbf, vWidth, height, 5);      //这里是比分
                vWidth = width / 4;
                addZJQ(vWidth, height, 4);
                vWidth = width / 3;
                addBQC(bqc, vWidth, height, 3);    //半球场*/

                break;


        }
    }

    /**
     * 这里要进行的一个操作就是显示所有的内容；
     *
     * @param isHuntou 如果是混投的话，我们要只显示胜分差别；
     */
    private void showAll(int height, int width, boolean isHuntou) {



        //显示胜负
        int vWidth = width / 2;
        addSF(vWidth, height, "0_sf_");


        //显示让胜负
        addRSF(vWidth, height, "1_rfsf_");


        //显示大小分
        addDXF(vWidth, height, "2_dxf_");

        //胜利分差
        mLlSfcContainer.setVisibility(View.VISIBLE);
        String[] sfc = mContext.getResources().getStringArray(
                R.array.jclq_sfc);
        String[] sfcValue = mContext.getResources().getStringArray(
                R.array.jclq_sfc_value);

        vWidth = width / 3;
        addSFC(sfc, sfcValue, vWidth, height, 3, "3_sfc_", 7);

        mRlSfc.setVisibility(View.VISIBLE);

        if (!isHuntou) {
            mLlSfContainer.setVisibility(View.VISIBLE);
            mLlRsfContainer.setVisibility(View.VISIBLE);
            mLlDxfContainer.setVisibility(View.VISIBLE);
        }

    }

    /**
     * map的key和list里面的key是不一样的；
     * 这里只有一行两列，我们可以简单的来处理
     *
     * @param width
     * @param height
     * @param perfix
     */
    private void addSF(int width, int height, String perfix) {
        //在code里面的索引值,获取赔率；
        int dataListIndex = 0;

        int firstTopMargin = 0;
        int firstLeftMargin = splitWidth;

        String odd = list.get(dataListIndex)[0];
        //拼写tag
        String tag = perfix + 0 + "_" + odd + "_" + "客胜" + "_" + 0;
        //这里拼接显示部分
        String str = showLQSFCText("客胜", odd);

        boolean isCheck = isCheckThisView(tag.toString(), "0");

        mRlSf.addView(createCheckBox(width, height, firstLeftMargin, firstTopMargin, str, tag, isCheck));


        //这里是第二个条目；
        int secondTopMargin = 0;
        int secondLeftMargin = width + splitWidth * 2;

        String odd2 = list.get(dataListIndex)[1];
        //拼写tag
        String tag2 = perfix + 1 + "_" + odd2 + "_" + "主胜" + "_" + 3;
        //这里拼接显示部分
        String str2 = showLQSFCText("主胜", odd2);
        boolean isCheck2 = isCheckThisView(tag2, "0");
        mRlSf.addView(createCheckBox(width, height, secondLeftMargin, secondTopMargin, str2, tag2, isCheck2));
    }


    /**
     * 这里只有一行两列，我们可以简单的来处理
     *
     * @param width
     * @param height
     * @param perfix
     */
    private void addRSF(int width, int height, String perfix) {
        //在code里面的索引值
        int dataListIndex = 1;

        int firstTopMargin = 0;
        int firstLeftMargin = splitWidth;

        String odd = list.get(dataListIndex)[1];
        //拼写tag
        String tag = perfix + 1 + "_" + odd + "_" + "客胜" + "_" + 0;
        //这里拼接显示部分
        String str = showLQSFCText("客胜", odd);

        boolean isCheck = isCheckThisView(tag.toString(), "1");

        mRlRsf.addView(createCheckBox(width, height, firstLeftMargin, firstTopMargin, str, tag, isCheck));


        //这里是第二个条目；
        int secondTopMargin = 0;
        int secondLeftMargin = width + splitWidth * 2;

        String odd2 = list.get(dataListIndex)[2];
        //拼写tag
        String tag2 = perfix + 2 + "_" + odd2 + "_" + "主胜" + "_" + 3;
        //这里拼接显示部分
        String str2 = showLQSFCText("主(" + list.get(dataListIndex)[0] + ")胜", odd2);
        boolean isCheck2 = isCheckThisView(tag2, "1");
        mRlRsf.addView(createCheckBox(width, height, secondLeftMargin, secondTopMargin, str2, tag2, isCheck2));
    }


    private void addDXF(int width, int height, String perfix) {
        //在code里面的索引值
        int dataListIndex = 2;

        int firstTopMargin = 0;
        int firstLeftMargin = splitWidth;

        String odd = list.get(dataListIndex)[1];
        //拼写tag
        String tag = perfix + 1 + "_" + odd + "_总分>" + list.get(dataListIndex)[0] + "_" + 0;
        //这里拼接显示部分
        String str = showLQSFCText("总分>" + list.get(dataListIndex)[0], odd);

        boolean isCheck = isCheckThisView(tag.toString(), "2");

        mRlDxf.addView(createCheckBox(width, height, firstLeftMargin, firstTopMargin, str, tag, isCheck));


        //这里是第二个条目；
        int secondTopMargin = 0;
        int secondLeftMargin = width + splitWidth * 2;

        String odd2 = list.get(dataListIndex)[2];
        //拼写tag
        String tag2 = perfix + 2 + "_" + odd2 + "_" + "总分<" + list.get(dataListIndex)[0] + "_" + 3;
        //这里拼接显示部分
        String str2 = showLQSFCText("总分&lt;" + list.get(dataListIndex)[0], odd2);
        boolean isCheck2 = isCheckThisView(tag2, "2");
        mRlDxf.addView(createCheckBox(width, height, secondLeftMargin, secondTopMargin, str2, tag2, isCheck2));
    }

    /**
     * 解析tag参数
     *
     * @param tag
     * @return
     */
    boolean isCheckThisView(String tag, String index) {
        if (this.map.get(index) != null) {
            return this.map.get(index).get(tag) != null;
        }
        return false;
    }


    /**
     * 返回比分和配置
     *
     * @param title
     * @param odd   return
     */
    public String showLQSFCText(String title, String odd) {

        StringBuilder str = new StringBuilder();
        str.append(title);
        str.append("<br/><small><small>");
        str.append(odd);
        str.append("</small></small>");
        return str.toString();
    }


    void addSFC(String[] sfc, String[] sfcValue, int width, int height, int maxLine, String perfix, int dataIndex) {
        int wm = 0;
        int hm = -splitWidth;
        //因为我从0的时候就+height 所有初始化的时候-height 就刚刚好是0
        int topMargin = -height;
        int leftMargin = ((maxLine - 1) * splitWidth) / 2;
        int index = 0;
        for (int i = 0; i < sfc.length; i++) {
            leftMargin += width;
            wm += ScreenUtil.dpToPx(mContext, 0.5f);
            if (index % maxLine == 0) {
                wm = 0;
                //这里初始化 ((maxLine - 1) * splitWidth) / 2 是由于两个格子都有边框 所有并排在一起的地方会很粗
                //我就将后一个的位置的边线与前一个重叠 然后重叠出来的空间 分配给整个容器左右两边当间距
                leftMargin = ((maxLine - 1) * splitWidth) / 2;
                topMargin += height;
                hm += splitWidth;
            }
            String game = i < 6 ? "客胜" : "主胜";
            StringBuilder str = new StringBuilder();
            str.append(sfc[i]);
            StringBuilder tag = new StringBuilder();
            tag.append(perfix + (i) + "_" + list.get(dataIndex)[i]);
            tag.append("_" + game + str.toString() + "_" + sfcValue[i].replaceAll("[+]", ""));
            str.append("<br/><small><small>");
            str.append(list.get(dataIndex)[i]);
            str.append("</small></small>");
            boolean isCheck = isCheckThisView(tag.toString(), "5");
            mRlSfc.addView(createCheckBox(width, height, leftMargin > 0 ? leftMargin - wm : leftMargin,
                    topMargin > 0 ? topMargin - hm : topMargin,
                    str.toString(), tag.toString(), isCheck));
            index++;
        }
    }


    private void initHeader() {
        //左边队名-公共属性
        mHomeTeamName.setText(codes[3]);
        //右边队名-公共属性
        mAwayTeamName.setText(codes[4]);

        mLlSfContainer.setVisibility(View.GONE);
        mLlRsfContainer.setVisibility(View.GONE);
        mLlDxfContainer.setVisibility(View.GONE);
        mLlSfcContainer.setVisibility(View.GONE);
    }

    CheckBox createCheckBox(int width, int height, int leftMargin, int topMargin, String text, String tag, boolean isCheck) {
        return createCheckBox(width, height, leftMargin, topMargin, text, tag, isCheck, -1, "");
    }


    /**
     * @param width      宽
     * @param height     高
     * @param leftMargin 左边距
     * @param topMargin  上边距
     * @param text       文本
     * @param tag        标记文本(携带下标-采种-倍数)
     * @param isCheck    是否选中
     * @param color      特殊文字变色
     * @param keyword    需要变色的特殊文字
     * @return
     */
    CheckBox createCheckBox(int width, int height, int leftMargin, int topMargin, String text, String tag, boolean isCheck, int color, String keyword) {
        CheckBox cb = new CheckBox(mContext);
        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(width, height);
        rl.leftMargin = leftMargin;
        rl.topMargin = topMargin;
        cb.setLayoutParams(rl);
        cb.setButtonDrawable(R.color.bh);
        cb.setTextColor(ContextCompat.getColorStateList(mContext, R.color.black_white_selector));
        cb.setGravity(Gravity.CENTER);
        cb.setBackgroundResource(R.drawable.red_white_selecter);
        cb.setTag(tag);
        cb.setText(Html.fromHtml(text));
//        cb.setText(StringUtils.matcherSearchText(color, text, keyword));
        cb.setChecked(isCheck);

/*       if(type.equals(JCZQSHOWTYPE.SHOWDG) && (tag.contains("rqspf") || tag.contains("spf"))) {
            cb.setText("未开售");
            cb.setEnabled(false);
            cb.setTextColor(ContextCompat.getColor(getContext(),R.color.b));
        }*/
        if (type.equals(JCZQSHOWTYPE.SHOWDG) && (tag.contains("rqspf"))) {
            //让胜平负是不支持单关的；所以这里我们是需要将其弄成未开售
            cb.setText("未开售");
            cb.setEnabled(false);
            cb.setTextColor(ContextCompat.getColor(getContext(), R.color.b));
        }
        return cb;
    }

    private OnSclestListener listener;

    public void setListener(OnSclestListener listener) {
        this.listener = listener;
    }


    @OnClick(R.id.tv_sure)
    void sure() {
        dismiss();
        Map<String, Map<String, String>> map = new LinkedHashMap<>();
        Map<String, String> spfCd = getCheckData(mRlSf);
        if (spfCd.size() > 0)
            map.put("0", spfCd);//0-1统一 0-spf 1-rqspf
        Map<String, String> rqspfCd = getCheckData(mRlRsf);
        if (rqspfCd.size() > 0)
            map.put("1", rqspfCd);//0-1统一 0-spf 1-rqspf

        Map<String, String> zjqCd = getCheckData(mRlDxf);
        if (zjqCd.size() > 0)
            map.put("2", zjqCd);

        Map<String, String> sfcCd = getCheckData(mRlSfc);
        if (sfcCd.size() > 0)
            map.put("5", sfcCd);
        if (listener != null)
            listener.sure(map);
    }


    private Map<String, String> getCheckData(ViewGroup v) {
        int count = v.getChildCount();
        Map<String, String> list = new HashMap<>();
        for (int i = 0; i < count; i++) {
            if (v.getChildAt(i) instanceof CheckBox) {
                CheckBox cb = (CheckBox) v.getChildAt(i);
                if (cb.isChecked()) {
                    list.put(cb.getTag().toString(), cb.getTag().toString());
                }
            }
        }
        return list;
    }


    @OnClick(R.id.tv_cancel)
    void close() {
        dismiss();
    }

}
